package com.cn.wanxi.message.task;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.cn.wanxi.message.socketserver.WebSocketServer;
import com.cn.wanxi.message.domain.MessageModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Log4j2
@Component
public class Scheduler {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Autowired
    private ObjectMapper objectMapper;

    /**
     * @MethodName sendCurTimeToOnlineUsers
     * @Description 给用户发送当前的时间
     * @Param []
     * @Return void
     **/
    //每分钟触发的任务
    @Scheduled(cron = "0 */1 * * * * ")
    public void sendCurTimeToOnlineUsers() throws JsonProcessingException {

        //根据当前的时间戳获取date对象
        Date now = new Date(System.currentTimeMillis());
        //格式化时间字符串
        String strDate = dateFormat.format(now);


        log.info("当前的系统时间为：{}", strDate);

        //创建发送的消息模型对象
        MessageModel msgModel = new MessageModel();
        //设置消息的接收者
        msgModel.setReceiver("all-online-user");

        //设置消息的发布者
        msgModel.setPublisher("system");

        //设置消息数据
        msgModel.setMessage(strDate);


        //群发消息给在线用户
        WebSocketServer.sendMsgToAllOnlineUser(objectMapper.writeValueAsString(msgModel));


    }

}